
package com.phevos.common.dbpool;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.phevos.common.dbpool.exception.DBPoolException;

public class TransactionManager
{
    private BasicConnectionPool myPool;

    private Connection myConnection = null;

    private boolean isAutoCommit = true;
    
    private static final Logger logger = LoggerFactory.getLogger(TransactionManager.class.getName());

    public TransactionManager() throws DBPoolException, SQLException
    {
        try
        {
            myPool = BasicConnectionPool.getInstance();
            myConnection = myPool.getConnection();
            // isAutoCommit = myConnection.getAutoCommit();
            // myConnection.setAutoCommit(false);
        }
        catch (java.sql.SQLException e)
        {
            logger.error("",e);
            throw e;
        }
    }

    public void beginTransaction()
    {
        try
        {
            isAutoCommit = myConnection.getAutoCommit();
            myConnection.setAutoCommit(false);
        }
        catch (java.sql.SQLException e)
        {
            logger.error("",e);
        }
    }

    public void endTransaction()
    {
        try
        {
            myConnection.setAutoCommit(isAutoCommit);
        }
        catch (Throwable t)
        {
            logger.error("",t);
        }
        try
        {
            myPool.returnConnection(myConnection);
        }
        catch (java.sql.SQLException e)
        {
            logger.error("",e);
        }
    }

    public void cancelTransaction()
    {
        try
        {
            myConnection.rollback();
            myConnection.setAutoCommit(isAutoCommit);
            myPool.returnConnection(myConnection);
        }
        catch (java.sql.SQLException e)
        {
            logger.error("",e);
        }
    }

    public void commit()
    {
        try
        {
            myConnection.commit();
        }
        catch (java.sql.SQLException e)
        {
            logger.error("",e);
        }
    }

    public void rollback()
    {
        try
        {
            myConnection.rollback();
        }
        catch (java.sql.SQLException e)
        {
            logger.error("",e);
        }
    }

    public Connection getConnection()
    {
        return myConnection;
    }
}
